import './style.css'
import { useEffect, useState } from 'react'
import { Button, Checkbox, message, Popconfirm, Tooltip, Typography } from 'antd'
import { useNavigate } from 'react-router-dom'
import { createOrderDraft, deleteShoppingCart, getOrderDraft, getShoppingCartList } from '@/api/shoppingCart.ts'
import { hsHandleTableDateTime } from '@hs-admin/utils'
import { clearLocalShopping } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { QuestionCircleFilled } from '@ant-design/icons'
import { HsAdminDataItemDetailModal } from '@hs-admin/components'

const { Text } = Typography

const ShoppingCart = () => {
  const navigate = useNavigate()
  const [itemList, setItemList] = useState([])

  const getList = () => {
    getShoppingCartList({
      page: 1,
      page_size: 9999
    }).then((res) => {
      setItemList(
        res.items.map((it) => ({
          ...it,
          checked: false
        }))
      )
    })
  }

  const [haveDraft, setHaveDraft] = useState(false)

  const [dataItemId, setDataItemId] = useState('')

  useEffect(() => {
    clearLocalShopping()
    getList()
    getOrderDraft()
      .then((res) => {
        if (res.items[0]) {
          setHaveDraft(true)
        } else {
          setHaveDraft(false)
        }
      })
      .catch(() => {
        setHaveDraft(false)
      })
  }, [])

  const product_ids = itemList.filter((it) => it.checked).map((it) => it.id)

  return (
    <div className="shopping-cart-wrapper">
      <h2 className="flex justify-between">
        购物车
        {haveDraft ? (
          <Button
            type="primary"
            onClick={() => {
              navigate('/submitShoppingOrder')
            }}>
            处理未完成草稿订单
          </Button>
        ) : (
          <Button
            type="primary"
            disabled={!product_ids.length}
            onClick={() => {
              if (product_ids.length) {
                createOrderDraft({
                  product_ids
                }).then(() => {
                  navigate('/submitShoppingOrder')
                })
              }
            }}>
            创建订单
          </Button>
        )}
      </h2>
      <div className="content-part">
        <div className="common-title-style justify-between">
          <span className="shop-title">已选数据项</span>
          <div className="flex gap-4">
            <Button
              type="primary"
              size="small"
              onClick={() => {
                navigate('/marketBasicData/themeDetail?id=')
              }}>
              新增数据项
            </Button>
          </div>
        </div>
        <div className="flex flex-col p6">
          <table className="w-full">
            <thead>
              <tr className="text-left ">
                <th className="font-black p2 whitespace-nowrap">
                  <Checkbox
                    disabled={haveDraft}
                    checked={itemList.length > 0 && itemList.every((it) => it.checked)}
                    onChange={(e) => {
                      const tobe = e.target.checked
                      setItemList((prevState) =>
                        prevState.map((it) => {
                          it.checked = tobe
                          return it
                        })
                      )
                    }}>
                    全选
                  </Checkbox>
                </th>
                <th className="font-black p2">数据项名称</th>
                <th className="font-black p2">英文表名</th>
                <th className="font-black p2">
                  支持筛选维度
                  <Tooltip overlayClassName="leading-8" title="红色：不支持；绿色：支持" color="#108ee9">
                    <QuestionCircleFilled />
                  </Tooltip>
                </th>
                <th className="font-black p2">添加时间</th>
                <th className="font-black p2">操作</th>
              </tr>
            </thead>
            <tbody>
              {itemList.map((item) => (
                <tr key={item.id}>
                  <td className="p2">
                    <Checkbox
                      disabled={haveDraft}
                      checked={item.checked}
                      onChange={(e) => {
                        setItemList((prevState) =>
                          prevState.map((it) => {
                            if (it.id === item.id) {
                              it.checked = e.target.checked
                            }
                            return it
                          })
                        )
                      }}></Checkbox>
                  </td>
                  <td className="p2 text-blue-500">
                    <Button
                      type="link"
                      onClick={() => {
                        setDataItemId(item.id)
                      }}>
                      {item.name}
                    </Button>
                  </td>
                  <td>{item.ref_table_name}</td>
                  <td className="p2">
                    <div className="flex gap-2">
                      {item.supported_specifications.map((it) => (
                        <Text
                          ellipsis={{ tooltip: true }}
                          style={{
                            maxWidth: '6em'
                          }}
                          key={it.name}
                          className={it.support ? 'text-green-400' : 'text-red-400'}>
                          {it.name}
                        </Text>
                      ))}
                    </div>
                  </td>
                  <td className="p2 whitespace-nowrap">{hsHandleTableDateTime(item.created_at)}</td>
                  <td className="p2">
                    <div className="flex gap-1">
                      <Popconfirm
                        title="删除该项"
                        description="确认删除吗?"
                        onConfirm={async () => {
                          await deleteShoppingCart(item.id)
                          getList()
                          message.success('删除成功')
                        }}
                        okText="确认"
                        cancelText="取消">
                        <span className="text-blue cursor-pointer whitespace-nowrap">删除</span>
                      </Popconfirm>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <HsAdminDataItemDetailModal id={dataItemId} onCancel={() => setDataItemId('')} />
    </div>
  )
}

export default ShoppingCart
